package com.stylefeng.guns.modular.transcapacitymag.controller;

import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.cache.CacheKit;
import com.stylefeng.guns.core.common.Tools.CodeMsg;
import com.stylefeng.guns.core.common.Tools.Result;
import com.stylefeng.guns.core.model.Pager;
import com.stylefeng.guns.core.validater.Insert;
import com.stylefeng.guns.core.validater.Update;
import com.stylefeng.guns.modular.netcar.model.OrderInf;
import com.stylefeng.guns.modular.netcar.service.IOrderInfService;
import com.stylefeng.guns.modular.transcapacitymag.model.PreOrderInf;
import com.stylefeng.guns.modular.transcapacitymag.model.dto.ConfirmPreOrderDTO;
import com.stylefeng.guns.modular.transcapacitymag.service.IPreOrderInfService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.stylefeng.guns.core.common.annotion.BussinessLog;

import java.util.Date;

@Controller
@RequestMapping(value = {"/gunsApi/auth/preOrderInf"})
@Api(value = "预下单信息操作相关api", tags = {"预下单信息操作接口"})
public class PreOrderInfController extends BaseController
{
    @Autowired
    private IPreOrderInfService preOrderInfService;

    @Value("${spring.validMinuteOrder}")//#订单未付款时预留票的时间 过后自动取消
    private String validMinuteOrder;

    @Autowired
    private IOrderInfService orderInfService;

    @ApiOperation(value = "分页获取预下单信息列表", notes = "分页获取预下单信息列表", httpMethod = "POST")
    @PostMapping(value = "/pageList", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Result pageList(
            @RequestBody @ApiParam(name = "preOrderInf", value = "预下单信息对象") PreOrderInf preOrderInf,
            @ApiParam(name = "pageNum", value = "当前页数", required = true) @RequestParam(value = "pageNum", required = true) Integer pageNum,
            @ApiParam(name = "pageSize", value = "每页显示条数", required = true) @RequestParam(value = "pageSize", required = true) Integer pageSize
    )
    {
        try
        {
            Pager pager = new Pager();
            pager.setPageNumber(pageNum);//页码从1 开始
            pager.setPageSize(pageSize);
            pager.setObj(preOrderInf);
            return Result.success(preOrderInfService.pageListPreOrderInf(pager, getToken()));
        }
        catch (Exception e)
        {
            return Result.error(CodeMsg.SERVER_EXCEPTION, e.getMessage());
        }
    }

    @ApiOperation(value = "获取预下单信息列表", notes = "获取预下单信息列表", httpMethod = "POST")
    @PostMapping(value = "/list", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Result list(@RequestBody @ApiParam(name = "preOrderInf", value = "预下单信息对象") PreOrderInf preOrderInf)
    {
        try
        {
            return Result.success(preOrderInfService.selectListPreOrderInf(preOrderInf, getToken()));
        }
        catch (Exception e)
        {
            return Result.error(CodeMsg.SERVER_EXCEPTION, e.getMessage());
        }
    }

    @ApiOperation(value = "通过主键获取预下单信息对象", notes = "通过主键获取预下单信息对象", httpMethod = "GET")
    @GetMapping(value = "/getById", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Result getById(@ApiParam(name = "id", value = "主键ID", required = true) @RequestParam(value = "id", required = true) String id)
    {
        try
        {
            return Result.success(preOrderInfService.findPreOrderInfById(id, getToken()));
        }
        catch (Exception e)
        {
            return Result.error(CodeMsg.SERVER_EXCEPTION, e.getMessage());
        }
    }

    @ApiOperation(value = "新增预下单信息数据", notes = "新增预下单信息数据", httpMethod = "POST")
    @PostMapping(value = "/add", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @BussinessLog(value = "新增预下单信息数据")
    @ResponseBody
    public Result add(@Validated(value = Insert.class) @RequestBody @ApiParam(name = "preOrderInf ", value = "预下单信息对象") PreOrderInf preOrderInf, BindingResult result)
    {
        if (result.hasErrors())
        {
            return Result.error(CodeMsg.SERVER_EXCEPTION, "参数异常！");
        }
        try
        {
            preOrderInfService.insertPreOrderInf(preOrderInf, getToken());
            return Result.success();
        }
        catch (Exception e)
        {
            return Result.error(CodeMsg.SERVER_EXCEPTION, e.getMessage());
        }
    }

    @ApiOperation(value = "更新预下单信息数据", notes = "更新预下单信息数据", httpMethod = "POST")
    @PostMapping(value = "/update", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @BussinessLog(value = "更新预下单信息数据")
    @ResponseBody
    public Result update(@Validated(value = Update.class) @RequestBody @ApiParam(name = "preOrderInf", value = "预下单信息对象") PreOrderInf preOrderInf, BindingResult result)
    {
        if (result.hasErrors())
        {
            return Result.error(CodeMsg.SERVER_EXCEPTION, "参数异常！");
        }
        try
        {
            preOrderInfService.updatePreOrderInf(preOrderInf, getToken());
            return Result.success();
        }
        catch (Exception e)
        {
            return Result.error(CodeMsg.SERVER_EXCEPTION, e.getMessage());
        }
    }

    @ApiOperation(value = "删除预下单信息数据", notes = "删除预下单信息数据", httpMethod = "GET")
    @GetMapping(value = "/delBatch", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @BussinessLog(value = "删除预下单信息数据")
    @ResponseBody
    public Result delBatch(@ApiParam(name = "ids", value = "主键ID字符数组", required = true) @RequestParam(value = "ids", required = true) String ids)
    {
        try
        {
            preOrderInfService.deleteBatchPreOrderInf(ids.split(","), getToken());
            return Result.success();
        }
        catch (Exception e)
        {
            return Result.error(CodeMsg.SERVER_EXCEPTION, e.getMessage());
        }
    }

    @ApiOperation(value = "删除预下单信息数据", notes = "删除预下单信息数据", httpMethod = "POST")
    @PostMapping(value = "/del", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @BussinessLog(value = "删除预下单信息数据")
    @ResponseBody
    public Result del(@RequestBody @ApiParam(name = "preOrderInf", value = "预下单信息对象") PreOrderInf preOrderInf)
    {
        try
        {
            preOrderInfService.deletePreOrderInf(preOrderInf, getToken());
            return Result.success();
        }
        catch (Exception e)
        {
            return Result.error(CodeMsg.SERVER_EXCEPTION, e.getMessage());
        }
    }

    @ApiOperation(value = "获取预下单信息的Key-Value列表，用于html的Select数据源", notes = "获取预下单信息的Key-Value列表，用于html的Select数据源", httpMethod = "POST")
    @PostMapping(value = "/optionsList", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Result optionsList(@RequestBody @ApiParam(name = "preOrderInf", value = "预下单信息对象") PreOrderInf preOrderInf)
    {
        try
        {
            return Result.success(preOrderInfService.optionsPreOrderInf(preOrderInf, getToken()));
        }
        catch (Exception e)
        {
            return Result.error(CodeMsg.SERVER_EXCEPTION, e.getMessage());
        }
    }

    @ApiOperation(value = "确认订单", httpMethod = "POST")
    @PostMapping(value = "/confirm", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Result confirmOrder(@RequestBody @ApiParam(name = "ConfirmPreOrderDTO", value = "确认订单数据") ConfirmPreOrderDTO confirmPreOrderDTO)
    {
        try
        {
            PreOrderInf preOrderInf = preOrderInfService.findPreOrderInfByIdForUpdate(confirmPreOrderDTO.preOrderId, getToken());
            if (preOrderInf == null)
            {
                return Result.error(CodeMsg.STATUS_OPERATE_FAILED, "订单信息不存在！");
            }

            if (!preOrderInf.getPayState().equals("1"))
            {
                return Result.error(CodeMsg.STATUS_OPERATE_FAILED, "订单不是已付款状态，无法确认！");
            }

            if (!preOrderInf.getConfirmState().equals("0"))
            {
                return Result.error(CodeMsg.STATUS_OPERATE_FAILED, "订单已被确认过或已过期！");
            }

            OrderInf orderInf = new OrderInf();
            orderInf.setOiId(preOrderInf.getOiId());
            orderInf.setOiCode(preOrderInf.getOiCode());
            orderInf.setOtId(preOrderInf.getOtId());
            orderInf.setOtName(preOrderInf.getOtName());
            orderInf.setOscId(preOrderInf.getOscId());
            orderInf.setOstId(preOrderInf.getOstId());
            orderInf.setOstName(preOrderInf.getOstName());
            orderInf.setOlId(preOrderInf.getOlId());
            orderInf.setOlName(preOrderInf.getOlName());
            orderInf.setCreateTime(preOrderInf.getCreateTime());
            orderInf.setCreateUser(preOrderInf.getCreateUser());
            orderInf.setUpdateTime(preOrderInf.getUpdateTime());
            orderInf.setUpdateUser(preOrderInf.getUpdateUser());
            orderInf.setCiId(preOrderInf.getCiId());
            orderInf.setCiName(preOrderInf.getCiName());
            orderInf.setCiTel(preOrderInf.getCiTel());
            orderInf.setCiNum(preOrderInf.getCiNum());
            orderInf.setCiTotalPrice(preOrderInf.getCiTotalPrice());
            orderInf.setOiDistance(preOrderInf.getOiDistance());
            orderInf.setOiOriginPrice(preOrderInf.getOiOriginPrice());
            orderInf.setOiDestPrice(preOrderInf.getOiDestPrice());
            orderInf.setBasePrice(preOrderInf.getBasePrice());
            orderInf.setDistancePrice(preOrderInf.getDistancePrice());
            orderInf.setTimePrice(preOrderInf.getTimePrice());
            orderInf.setDatePrice(preOrderInf.getDatePrice());
            orderInf.setOiStartAddress(preOrderInf.getOiStartAddress());
            orderInf.setOiStartPoint(preOrderInf.getOiStartPoint());
            orderInf.setOiEndAddress(preOrderInf.getOiEndAddress());
            orderInf.setOiEndPoint(preOrderInf.getOiEndPoint());
            orderInf.setCiSendTime(preOrderInf.getCiSendTime());
            orderInf.setPayState(preOrderInf.getPayState());
            orderInf.setPayFee(preOrderInf.getPayFee());
            orderInf.setPayTime(preOrderInf.getPayTime());
            orderInf.setOiExternalOrderId(preOrderInf.getOiExternalOrderId());
            orderInf.setOiQrcode(preOrderInf.getOiQrcode());
            orderInf.setOiOrderTimeStart(preOrderInf.getOiOrderTimeStart());
            orderInf.setOiOrderTimeEnd(preOrderInf.getOiOrderTimeEnd());
            orderInf.setOiContainInvoice(preOrderInf.getOiContainInvoice());
            orderInf.setNote(preOrderInf.getNote());
            orderInf.setExSendTime(preOrderInf.getExSendTime());
            orderInf.setExArrTime(preOrderInf.getExArrTime());
            orderInf.setExFlightLeg(preOrderInf.getExFlightLeg());
            orderInf.setExOtherNo(preOrderInf.getExOtherNo());
            orderInf.setExTicketNo(preOrderInf.getExTicketNo());
            orderInf.setVptCode(preOrderInf.getVptCode());
            orderInf.setCouponFee(preOrderInf.getCouponFee());
            //ci_valid_time字段存储过期时间，不与order_inf表的ci_valid_time作用相同
            orderInf.setCiValidTime(new Date(new Date().getTime() + (Integer.parseInt(validMinuteOrder) * 60000)));
            orderInf.setOiPackageState("0");
            orderInf.setCiState("0");
            orderInf.setPayState("0");
            orderInf.setOiAutoPackaged("0");
            orderInf.setOiNewFlg("1");

            if (orderInfService.insertOrderInf(orderInf, getToken(), true) == 0)
            {
                //统计新订单数量 提醒调度员
                String olId = preOrderInf.getOlId();
                if (CacheKit.getKeys("globalForeverCache").contains(preOrderInf.getOiId()))
                {
                    int newOrderNum = (Integer) CacheKit.get("globalForeverCache", olId);
                    newOrderNum = newOrderNum + 1;
                    CacheKit.put("globalForeverCache", olId, newOrderNum);
                }
                else
                {
                    CacheKit.put("globalForeverCache", olId, 1);
                }

                preOrderInf.setConfirmState("1");
                preOrderInf.setConfirmTime(new Date());
                preOrderInf.setConfirmPsn(confirmPreOrderDTO.userId);

                if (preOrderInfService.updatePreOrderInf(preOrderInf, getToken()) == 1)
                {
                    return Result.success();
                }
            }

            return Result.error(CodeMsg.STATUS_OPERATE_FAILED, "操作失败，请稍后再试！");
        }
        catch (Exception e)
        {
            return Result.error(CodeMsg.SERVER_EXCEPTION, e.getMessage());
        }
    }

    private String getToken()
    {
        return getHttpServletRequest().getHeader("Authorization").substring(7);
    }
}
